package com.pjh.shitang.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pjh.shitang.entitys.Food;
import com.pjh.shitang.entitys.Likes;
import com.pjh.shitang.entitys.Window;
import com.pjh.shitang.mappers.FoodMapper;
import com.pjh.shitang.mappers.LikesMapper;
import com.pjh.shitang.mappers.WindowMapper;
import com.pjh.shitang.services.WindowService;
import com.pjh.shitang.utils.vo.receive.PageInfo;
import com.pjh.shitang.utils.vo.returns.DataWithLike;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * @author yueyinghaibao
 * @date 2022/5/6
 */
@Service
public class WindowServiceImpl implements WindowService {

    @Resource
    WindowMapper windowMapper;

    @Resource
    FoodMapper foodMapper;

    @Resource
    LikesMapper likesMapper;

    @Override
    public List<DataWithLike<Object>> queryPage(PageInfo info) {
        List<DataWithLike<Object>> list = new ArrayList<>();

        if("window".equals(info.getType())) {
            Page<Window> page1 = new Page<>(info.getPage(), info.getSize());
            page1 = windowMapper.selectPage(page1, new QueryWrapper<>());
            for(Window c : page1.getRecords()) {
                list.add(new DataWithLike<>(c,
                        likesMapper.selectCount(new LambdaQueryWrapper<Likes>()
                                .eq(Likes::getFroms, info.getFroms())
                                .eq(Likes::getTos, c.getWid())
                                .eq(Likes::getType, "window")) > 0));
            }
        } else {
            Page<Food> page1 = new Page<>(info.getPage(), info.getSize());
            page1 = foodMapper.selectPage(page1, new QueryWrapper<Food>().eq("wid", info.getTos()));
            for(Food c : page1.getRecords()) {
                list.add(new DataWithLike<>(c,false));
            }
        }

        return list;
    }

    @Override
    public Map<String, Object> dinnerRoll(Integer code) {
        Random r = new Random();
        Integer mx = foodMapper.searchMaxFid();
        int id = Math.abs(r.nextInt()) % mx;

        Food food = foodMapper.searchOneByFid(id);
        Window window = windowMapper.selectById(food.getWid());

        Map<String, Object> map = new TreeMap<>();
        map.put("window", window);
        map.put("food", food);

        return map;
    }
}
